"use restrict";

var tool = require('./jtool.js');
var Excel = require('exceljs');
var asyn = require("async");
var fs = require('fs');
var sql3 = require("sqlite3");
sql3.verbose();
var jq = require("cheerio");

var g = {
    u1: "http://122.225.121.106:8088/scdeap/sydwglAction.do?method=select",
    u1a: "http://122.225.121.106:8088/scdeap/sydwglAction.do?method=device_all",
    u2: "http://122.225.121.106:8088/scdeap/sydwglAction.do?method=edit",
    p1: {
        "header": {
            "Content-Type": "application/x-www-form-urlencoded",
            "Cookie": "JSESSIONID=D4D897BCF4C9AF088CFE0F093899ABFB; cd_6107=''; iswbzh=0; cod=JC_DWDA; csd=JC_DWDASY"
        },
        "charset": "utf-8",
    },
    p2: {
        "header": {
            "Cookie": "JSESSIONID=D4D897BCF4C9AF088CFE0F093899ABFB; cd_6107=''; iswbzh=0; cod=JC_DWDA; csd=JC_DWDASY"
        },
        "charset": "utf-8",
    },
    d1: "method=select&ec_i=ec&eti=&eti_p=&ec_efn=&ec_ev=&ec_crd=10&ec_f_a=&ec_p=1&ec_s_USEDEPTNAME=\
        &ec_s_PARTICULARADDR=&ec_s_ORGANCODE=&ec_s_AREACODE_NAME=&ec_s_GOVERNORTEL=&ec_s_GOVERNOR=\
        &SYSFUNCODE=JC_DWDASY&ec_totalpages=0&ec_totalrows=&ec_f_radio&ec_pg=1&ec_rd=10\
        &ec_f_序号=&ec_f_操作=&ec_f_设备=&ec_f_人员=&ec_f_USEDEPTNAME=&ec_f_PARTICULARADDR=\
        &ec_f_ORGANCODE=&ec_f_AREACODE_NAME=&ec_f_GOVERNORTEL=&ec_f_GOVERNOR=&USEDEPTSYSID=\
        &ORGANCODE=&AREACODE=330523&areacodecontent1=330000&areacodecontent2=330500&areacodecontent3=330523\
        &areacodecontent4=&OIDNO=&EQUTYPE=&EQUTYPE1=&EQUIP=&EQUIP1=&PERSON=&PERSON1=&PCSJX=&PCSJXNR=\
        ",//&USEDEPTNAME=
    d1a: "method=device_all&ec_i=ec&eti=&eti_p=&ec_efn=&ec_ev=&ec_crd=500&ec_f_a=&ec_p=1&ec_s_EQULOGCODE=\
        &ec_s_EQUORGNO=&ec_s_EQUCLACODE=&ec_s_EQUIPNAME=&ec_s_PRONO=&ec_s_EQUCODE=&ec_s_USECARNO=\
        &ec_s_USEORGNAME=&ec_s_DEPARTNAME=&ec_s_NINSPDATE=&ec_s_USSTATUS=&ec_s_LOGINSTATE=\
        &ec_totalpages=1&ec_totalrows=500&ec_f_radio=&ec_s_EQUIPMODEL=\
        &ec_f_null=&ec_f_%E5%BA%8F%E5%8F%B7=&ec_f_EQULOGCODE=&ec_f_EQUIPMODEL=&ec_f_EQUORGNO=\
        &ec_f_EQUCLACODE=&ec_f_EQUIPNAME=&ec_f_PRONO=&ec_f_EQUCODE=&ec_f_USECARNO=&ec_f_USEORGNAME=\
        &ec_f_DEPARTNAME=&ec_f_NINSPDATE=&ec_f_USSTATUS=&ec_f_LOGINSTATE=&ec_pg=1&ec_rd=500\
        ",//&USEORGSYSNO=&EQUCLACODE=
    d2: "method=edit",//&USEDEPTSYSID=
    limit: 5,
    dws: [],
    wb: new Excel.Workbook(),
    db: new sql3.Database("../test.db", test),
}
//main
function test(err) {
    if (err) throw err;
    asyn.series([
        callback => {
            g.db.exec(fs.readFileSync('./test.sql', 'utf-8'), err => {
                if (err) throw err;
                g.db.each('select sydw from user', (err, row) => {
                    if (err) throw err;
                    g.dws.push(row.sydw);
                }, (err, cnt) => {
                    if (err) throw err;
                    g.wb.xlsx.readFile('../bb.xlsx')
                        .then(() => {
                            callback(null);
                        });
                });
            });
        },
        callback => {
            asyn.series([
                callback => {
                    getR1(callback);
                },
                callback => {
                    getR2(callback);
                }
            ], (err, res) => {
                if (err) throw err;
                callback(null);
            });
        },
    ], (err, res) => {
        if (err) console.log(err);
        console.log('all task is finished!');
    });
}
//collect sys_id by sydw
function getR1(callback) {
    var rs = new Array(),
        worksheet = g.wb.getWorksheet(1),
        idw;
    worksheet.eachRow((row, idx) => {
        idw = row.getCell(3).value;
        if (g.dws.indexOf(idw) < 0) {
            rs.push({
                sydw: idw,
                dwid: '',
                rds: new Array()
            });
        }
    });
    console.log('task is beginnig! Num: ' + rs.length);//log A
    asyn.mapLimit(rs, g.limit, (ri, callback) => {
        console.log(rs.indexOf(ri) + ': ' + ri.sydw);//log B
        tool.post(g.u1, g.p1, encodeURI(g.d1 + '&USEDEPTNAME=' + ri.sydw))
            .then(res => {
                var arr = res.text.match(/onclick=\"do_device_count\(\'([^\'\(\)]+)\'\)\"/i);
                if (!arr) {
                    callback(null);
                    return;
                }
                ri.dwid = arr[1];
                getR1a(ri, callback);
            })
            .catch(err => {
                if (err) throw err;
            });
    }, (err, res) => {
        if (err) throw err;
        callback(null);
    });
}
//collect all devices by sydw
//EQUCLACODE:   锅炉(1000)-压力容器(2000)-压力管道(8000)-电梯(3000)-起重机械(4000)-
//              厂内机动车辆(5000)-大型游乐设施(6000)-客运索道(9000)
function getR1a(ri, callback) {
    tool.post(g.u1a, g.p1, encodeURI(g.d1a + '&USEORGSYSNO=' + ri.dwid + '&EQUCLACODE='))
        .then(res => {
            // fs.writeFileSync('../ss.txt', res.text);
            var $ = jq.load(res.text),
                w = new Array(16),
                s;
            var stmt = g.db.prepare("INSERT INTO device VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
            $('#ec_table_body tr').each((i, ei) => {
                $(ei).children().each((j, ej) => {
                    if (j == 1) {
                        s = $(ej).html().match(/do_edit\(([^\)]+)\)/i);
                        s = $('<div>').html(s[1]).text();
                        s = s.match(/'([^']+)','([^']+)','([^']+)'/i);
                        if (!s) {
                            w[0] = null;
                            return;
                        }
                        w[0] = s[1];
                        w[1] = s[2];
                        w[2] = s[3];
                    }
                    if (j < 3) return;
                    w[j] = $(ej).text();
                });
                if (w[0]) stmt.run(w);
            });
            stmt.finalize(err => {
                if (err) throw err;
                g.db.run('INSERT INTO user VALUES (?,?,?,?,?,?,?)',
                    [ri.dwid, ri.sydw, null, null, null, null, null], err => {
                        callback(null);
                    });
            });
        })
        .catch(err => {
            if (err) throw err;
        });
}
//collect sydw information
//安吉县(330523XX):递铺街道(01),梅溪镇(02),天子湖镇(03),孝丰镇(04),报福镇(05)
//                  章村镇(06),天荒坪镇(07),溪龙乡(10),孝源街道(11),上墅乡(12)
//                  山川乡(13),昌硕街道(14),灵峰街道(15),鄣吴镇(16),杭垓镇(17)
function getR2(callback) {
    var rs = new Array();
    g.db.each('select dwid,sydw,addr from user', (err, row) => {
        if (err) throw err;
        if (row.addr) return;
        rs.push([row.sydw, '', '', '', '', '', row.dwid]);
    }, (err, cnt) => {
        if (err) throw err;
        asyn.mapLimit(rs, g.limit, (ri, callback) => {
            console.log(rs.indexOf(ri) + ': ' + ri[0]);//log B
            tool.post(g.u2, g.p2, encodeURI(g.d2 + '&USEDEPTSYSID=' + ri[6]))
                .then(res => {
                    // fs.writeFileSync('../ss1.txt', res.text);
                    var $ = jq.load(res.text);
                    ri[1] = $('input[name=PARTICULARADDR]').first().attr('value');
                    ri[2] = $('input[name=ORGANCODE]').first().attr('value');
                    ri[3] = $('input[name=AREACODE]').first().attr('value');
                    ri[4] = $('input[name=GOVERNOR]').first().attr('value');
                    ri[5] = $('input[name=GOVERNORTEL]').first().attr('value');
                    g.db.run('UPDATE user SET addr=?,jgdm=?,dqdm=?,lxrn=?,lxdh=? WHERE dwid=?',
                        ri.slice(1), err => {
                            if (err) throw err;
                            callback(null);
                        });
                })
                .catch(err => {
                    if (err) throw err;
                });
        }, (err, res) => {
            if (err) throw err;
            callback(null);
        });
    });

}

